const SystemErrException = require("../exception/systemError");

const getOpenId = async function (ctx, wxConfig) {
  try {
    const urlStr = "https://api.weixin.qq.com/sns/jscode2session";
    const data = {
      ...wxConfig,
      grant_type: "authorization_code", // 受权类型，此处只需填写 authorization_code
    };
    const result = await ctx.curl(urlStr, {
      data: data,
      dataType: "json",
    });
    if (result.data.errmsg) {
      throw new SystemErrException(`获取微信openid异常：${result.data.errcode}，${result.data.errmsg}`);
    } else {
      return {
        openid: result.data.openid,
        session_key: result.data.session_key
      }
    }
  } catch (error) {
    throw new SystemErrException("获取微信openid异常：" + error);
  }
};

const getAccessToken = async function (ctx) {
  try {
    const { currentUserId: id } = ctx;
    let user = await ctx.model.User.findByPk(id);
    user = JSON.parse(JSON.stringify(user));
    const { appId, appSecret } = user;
    const urlStr = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`;
    const result = await ctx.curl(urlStr, {
      dataType: "json"
    });
    if (result.data.access_token) {
      return result.data.access_token;
    } else {
      throw new SystemErrException("获取 AccessToken 异常：" + error);
    }
  } catch (error) {
    throw new SystemErrException("获取 AccessToken 异常：" + error);
  }
}

const getwxacode = async function (ctx, id) {
  try {
    const { accessToken } = ctx;
    const urlStr = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`
    const codeData = {
      // env_version: 'develop',
      check_path: false,
      page: 'pages/home/home',
      scene: `id=${id}`
    }
    const result = await ctx.curl(urlStr, {
      method: 'POST',
      data: codeData,
      contentType: 'json'
    });
    if (result.status === 200) {
      return result.data;
    } else {
      throw new SystemErrException("获取小程序二维码失败：" + error);
    }
  } catch (error) {
    throw new SystemErrException("获取小程序二维码失败：" + error);
  }
}

module.exports = {
  getOpenId,
  getwxacode,
  getAccessToken
};
